package demo;

import java.util.concurrent.*;

/**
 * 简单模拟线程池核心功能
 * 固定核心线程数量
 */

class MyThreadPool{
    private BlockingQueue<Runnable> queue=new ArrayBlockingQueue<>( 1000);

    public MyThreadPool(int n){//此处的n表示可以创建几个线程
        for (int i = 0; i < n; i++) {
            Thread t=new Thread(()->{
                while(true){
                    try {
                        Runnable runnable = queue.take();
                        runnable.run();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            });
            t.start();
        }
    }

    /**
     * 添加任务
     * @param runnable
     */
    public void submit(Runnable runnable){
        try{
            queue.put(runnable);
        }catch (InterruptedException e){
            throw new RuntimeException(e);
        }
    }
}

public class demo3 {
    public static void main(String[] args) {
        MyThreadPool pool=new MyThreadPool(5);
        for (int i = 0; i < 100; i++) {
            int id=i;
            pool.submit(()->{
                System.out.println("执行任务"+id+";"+Thread.currentThread().getName());
            });
        }
    }

    public static void main1(String[] args) throws InterruptedException {
        ExecutorService service= Executors.newFixedThreadPool(5);
        for (int i = 0; i < 100; i++) {
            int id=i;
            service.submit(()->{
                System.out.println("执行任务"+id+";"+Thread.currentThread().getName());
            });
        }
        // 最好不要立即就终止, 可能使任务还没执行完呢, 线程就被终止了.
        Thread.sleep(2000);

        // 关闭线程池
        service.shutdown();
        System.out.println("程序退出");
    }
}
